<template>
  <!-- 右侧菜单栏的所有元素的拉框查询 -->
  <div>
    <!-- 矩形查询 -->
    <el-menu-item class="alldraw-query" index="0-1" @click="activeDraw('Box')">
      <el-icon><FullScreen /></el-icon>
      拉框查询
    </el-menu-item>
    <!-- 画圆查询 -->
    <el-menu-item
      class="alldraw-query"
      index="0-2"
      @click="activeDraw('Circle')"
    >
      <!-- ⚪ -->
      <el-icon><Aim /></el-icon>
      画圆查询
    </el-menu-item>
  </div>
  <!-- 拉框之后的对话框 -->
  <el-dialog
    v-model="dialogVisible"
    title="查询结果"
    width="700px"
    draggable
    :modal="false"
    append-to-body
    :destroy-on-close="true"
    @close="closeDialog"
  >
    <div class="dia_content">
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <div class="pane_outer" v-if="msg_obj">
          <el-tab-pane
            :label="key"
            :name="index"
            v-for="(value, key, index) in msg_obj"
            :key="key"
          >
            <el-table
              :data="
                value.slice(
                  (currentPage - 1) * pageSize,
                  currentPage * pageSize
                )
              "
              border
              style="width: 100%"
              height="350"
            >
              <!-- <el-table-colum label="序号">
                <templete #default="scope">
                  {{ scope.$index + 1 }}
                </templete>
              </el-table-colum> -->
              <el-table-column
                :prop="key_"
                :label="key_"
                width="180"
                v-for="(value_, key_) in value[0]"
                :key="key_"
              />
            </el-table>
            <!-- 分页 -->
            <div class="demo-pagination-block">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[5, 7, 10]"
                :small="true"
                :disabled="false"
                :background="true"
                layout="total, sizes, prev, pager, next, jumper"
                :total="value.length"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </el-tab-pane>
        </div>
      </el-tabs>
    </div>
  </el-dialog>
</template>

<script setup>
// 导入画笔
import { createDraw } from "../../../../../utils/createDraw.js";
// 导入Query查询工具
import { Query } from "../../../../../utils/Query.js";
// 对话框的显隐
const dialogVisible = ref(false);
// 对话框tab栏切换
const activeName = ref(0);
// 对话框tab栏切换点击事件函数
const handleClick = (tab, evt) => {
  // console.log(tab,evt);
  currentPage.value = 1;
};
// 表格分页
const currentPage = ref(1);
const pageSize = ref(5); // 每页的个数
const handleSizeChange = (val) => {
  // 改变每页大小
  // console.log(val, "size");
  pageSize.value = val;
};
const handleCurrentChange = (val) => {
  // 改变当前页
  // console.log(val, "current");
  currentPage.value = val;
};
// 查询得到的不同元素的对象信息放入这个对象
const msg_obj = ref(null);
let $map = null;
// 事件高亮图层的数据源 //（等待mounted中注入）
let $evtSource = null;
// 创建画笔数据源【与EDrawSearch共用同一个画笔数据源】
// let sourceDraw = new ol.source.Vector({
// });
let sourceDraw = inject("$sourceDraw");
// 画笔图层
let draw_layer = new ol.layer.Vector({
  source: sourceDraw,
  // zIndex:5
});
// console.log(draw_layer, sourceDraw);
// console.log(draw_layer.getSource());
onMounted(() => {
  $map = inject("$map");
  $map.addLayer(draw_layer);
  // 注入 $evtSource // 事件高亮图层的数据源 (来自ekeywords)
  $evtSource = inject("$evtSource");
});
//定义画笔
let draw = null;

// 函数：点击拉框按钮后的函数
function activeDraw(type) {
  // 创建画笔
  draw = createDraw({
    type,
    source: sourceDraw,
  });
  // 画笔添加到地图
  $map.addInteraction(draw);
  // 设置画笔结束事件
  draw.on("drawend", (evt) => {
    // 打开对话框【准备展示数据】
    dialogVisible.value = true;
    // draw_layer.getSource().addFeature(feature)
    // 画笔结束，清空画笔的数据源，这样画笔就消失了
    // sourceDraw.clear();
    // 移除画笔
    $map.removeInteraction(draw);
    // 获取画笔要素
    let geometry = evt.feature.getGeometry();
    // console.log(geometry);
    //  设置查询图层 Point
    // let service = {
    //   name: "guanggu",
    //   layerId: 2,
    // };
    // // 根据画笔要素查询Point图层
    // Query.queryByGeom({
    //   geometry,
    //   service,
    //   success,
    //   type,
    // });
    // 根据画笔要素遍历查询所有图层，并将结果赋值给ms_obj的属性
    for (let i = 0; i <= 4; i++) {
      Query.queryByGeom({
        geometry,
        service: {
          name: "guanggu",
          layerId: i,
        },
        success: (result) => {
          // console.log(i)
          success(result, i);
        },
        type,
      });
    }
  });
}
//查询成功回调
const msg_obj_initial = {
  居民区: [],
  武汉光谷道路: [],
  事件: [],
  摄像头: [],
  警务室: [],
};
let count = 0; // 第几次调用回调
function success(result, i) {
  count++;
  let format = new Zondy.Format.PolygonJSON();
  //将MapGIS要素JSON反序列化为ol.Feature类型数组
  let features = format.read(result);
  // console.log(features, i);
  let layer_name_arr = ["居民区", "武汉光谷道路", "事件", "摄像头", "警务室"];
  if (features) {
    // $evtSource.clear()
    // $evtSource.addFeatures(features);
    // console.log(msg_obj.value[Object.keys(msg_obj.value)[i]]);// 数组[]
    msg_obj_initial[Object.keys(msg_obj_initial)[i]] = features.map((item) => {
      let obj = item.values_.values_;
      delete obj.mpLayer;
      return obj; // 如果没有要素，map对空数组返回的是空数组
    });
    if (count === 5) {
      // console.log(msg_obj_initial); // 最终要渲染表格的数据结构
      msg_obj.value = msg_obj_initial;
      msg_obj.value.事件 = msg_obj_initial.事件.map((item) => {
        item.处理状态 =
          item.处理状态 === "0"
            ? "待处理"
            : item.处理状态 === "1"
            ? "处理中"
            : "已归档";

        item.事件等级 =
          item.事件等级 === "1"
            ? "轻微事故"
            : item.事件等级 === "2"
            ? "一般事故"
            : item.事件等级 === "3"
            ? "重大事故"
            : "特大事故";

        return item;
      });
      count = 0;
      // console.log(msg_obj.value, 999999);
    }
  }
}
// 关闭对话框的回调
function closeDialog() {
  // console.log(1);
  // 清除画笔数据源
  sourceDraw.clear();
}
</script>

<style lang="scss" scoped>
// 分页盒子的样式
.demo-pagination-block {
  margin-top: 10px;
}
// tab栏内容的样式
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
.el-menu-item.alldraw-query {
  height: 40px;
}
</style>
